package com.example.toolsdemo.service.impl;

import com.example.toolsdemo.common.ServerResponse;
import com.example.toolsdemo.dataobject.Orders;
import com.example.toolsdemo.mapper.OrderMapper;
import com.example.toolsdemo.service.OrderService;
import com.example.toolsdemo.utils.PagedGridResult;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.n3r.idworker.Sid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;

@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private Sid sid;

    @Override
    public Orders getOrder(String id) {
        return orderMapper.selectByPrimaryKey(id);
    }

    @Override
    public Integer saveOrder(Orders order) {
        order.setId(sid.nextShort());
        order.setCreateTime(new Date());
        order.setUpdateTime(new Date());
        return orderMapper.insert(order);
    }

    @Override
    public ServerResponse modifyOrder(Orders order) {

        if (order.getId() == null) {
            return ServerResponse.error("orderId不能为空");
        }
        int updateResult = orderMapper.updateByPrimaryKeySelective(order);
        if (updateResult > 0) {
            return ServerResponse.success("更新成功");
        }
        return ServerResponse.error("更新失败");
    }

    @Override
    public Integer deleteOrder(String id) {
        return orderMapper.deleteByPrimaryKey(id);
    }

    @Override
    public ServerResponse getOrdersByUserId(String userId, Integer pageNum, Integer pageSize) {

        Example orderExample = new Example(Orders.class);
        Example.Criteria criteria = orderExample.createCriteria();
        criteria.andEqualTo("userId", userId);
        PageHelper.startPage(pageNum, pageSize);
        List<Orders> orderList = orderMapper.selectByExample(orderExample);
        PagedGridResult pagedGridResult = setterPagedGrid(orderList, pageNum);
        return ServerResponse.success(pagedGridResult);
    }

    private PagedGridResult setterPagedGrid(List<?> list, Integer page) {
        PageInfo<?> pageList = new PageInfo<>(list);
        PagedGridResult grid = new PagedGridResult();
        grid.setPage(page);
        grid.setRows(list);
        grid.setTotal(pageList.getPages());
        grid.setRecords(pageList.getTotal());
        return grid;
    }
}
